package com.wk.myhandle;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

/**
 *  互斥队列的通用类
 */
public class MyMessageQueue {

    //声明阻塞队列
    private BlockingDeque blockingDeque = new LinkedBlockingDeque(50);

    /**
     * 入队（生产者）
     * @param msg
     * @return
     */
    public void enqueueMessage(MyMessage msg) {
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }
        try {
            blockingDeque.put(msg);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 出队（消费者）
     * @return
     */
    public MyMessage next() {
        MyMessage msg = null;
        try {
            msg = (MyMessage) blockingDeque.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (Exception e){
            e.printStackTrace();
        }
        return msg;
    }
}